import traceback

from air_web.config.config import config
from air_web.data_platform import mysql_con, redis_con


class ModelMap:
    get_map = {}

    @staticmethod
    def _column(column):
        column_list = column.split("_")
        column = "".join([i.capitalize() for i in column_list])
        return column

    @staticmethod
    def get(
        column: str,
        key,
        error_ignore=False,
        value="",
        reverse=False,
        db_key=None,
    ):
        org_name = column
        column = ModelMap._column(str(column))
        try:
            tmp_map = ModelMap.get_map.get(org_name)
            if tmp_map["save_type"] == "memory":
                key_map = globals()[org_name]
            elif db_key is not None and tmp_map["save_type"] == "redis":
                key_map = redis_con.hget(db_key, key)
                key_map = {key: key_map.decode()}
            elif db_key is not None and tmp_map["save_type"] == "mysql":
                sql = f"select {key} from {tmp_map['table_name']} where {tmp_map['key']} = '{db_key}' "
                result = mysql_con.get(sql)
                # mysql要直接return
                if result == []:
                    key_map = {}
                else:
                    key_map = {key: result[0][key]}
            else:
                key_map = eval(column).key_map

            if reverse:
                key_map = dict(map(reversed, key_map.items()))
            return key_map.get(key)
        except Exception as e:
            if error_ignore:
                return value
            else:
                raise e

    @staticmethod
    def get_all(column: str, reverse=False):
        try:
            result = {}
            for _c in column.split(";"):
                org_c = _c
                _c = ModelMap._column(_c)
                tmp_map = ModelMap.get_map.get(org_c)

                if tmp_map["save_type"] == "memory":
                    key_map = globals()[org_c]
                elif tmp_map["save_type"] == "redis":
                    return {}
                elif tmp_map["save_type"] == "mysql":
                    return {}
                else:
                    key_map = eval(_c).key_map

                if reverse:
                    result[org_c] = dict(map(reversed, key_map.items()))
                else:
                    result[org_c] = key_map

            if ";" in column:
                return result
            else:
                return result[column]

                # column = ModelMap._column(column)
                # if reverse:
                #     return dict(map(reversed, eval(column).key_map.items()))
                # else:
                #     return eval(column).key_map
        except Exception as e:
            raise PermissionError(f"1006：{e}")

    def get_data(self, table_name, column, key):
        column.append(key)
        sql = f"select {','.join(column)} from {table_name}"
        result = mysql_con.get(sql)
        return result

    def execute_task(self):
        tasks = config["map_task"]
        for task in tasks:
            task = config["map_task"][task]
            tmp_res = self.get_data(
                task["table_name"], task["column"], task["key"]
            )
            self.get_map[task["save_name"]] = task
            if task["save_type"] == "memory":
                globals()[task["save_name"]] = {
                    i[task["key"]]: i[task["column"][0]] for i in tmp_res
                }
            # elif task['save_type'] == 'redis':
            #     for i in tmp_res:
            #         redis_con2.hmset(i[task['key']], i)


class TypeCodeSort:
    def __repr__(self):
        return "类别类型"

    key_map = {"1": "专变用户", "2": "低压用户"}


try:
    ModelMap().execute_task()
except:
    print(traceback.format_exc())
